package vip.web3.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.EnumMap;

public class QRcode {

	/**
	 * 二维码生成
	 * @param content
	 * @return
	 * @throws Exception 
	 */
	public static String getEncode(String content){
		//二维码颜色
		final int BLACK = 0xFF000000;//0xFFFF0000，红色
		//二维码背景色
		final int WHITE = 0xFFFFFFFF;//0xFF0000FF，蓝色
		//注：二维码颜色色差大，扫描快，但如果"BLACK'设置为黑色外其他颜色，可能无法扫描
		//二维码图片宽度
		final int WIDTH = 240;
		//二维码图片高度
		final int HEIGHT = WIDTH;
		//二维码格式参数
		final EnumMap<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
		/*二维码的纠错级别(排错率),4个级别：
		 L (7%)、
		 M (15%)、
		 Q (25%)、
		 H (30%)(最高H)
		 纠错信息同样存储在二维码中，纠错级别越高，纠错信息占用的空间越多，那么能存储的有用讯息就越少；共有四级；
		 选择M，扫描速度快。
		 */
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 二维码边界空白大小 1,2,3,4 (4为默认,最大)
		hints.put(EncodeHintType.MARGIN, 1);
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		hints.put(EncodeHintType.MAX_SIZE, 350);
		hints.put(EncodeHintType.MIN_SIZE, 150);
		
		BufferedImage image = null;
		ByteArrayOutputStream stream = null;
		try{
			BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
			matrix = deleteWhite(matrix);//去除白边
			image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
				
			int width = matrix.getWidth();
			int height = matrix.getHeight();
			for(int x = 0; x < width; x++){
				for(int y =0;y < height; y++){
					image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
				}
			}
//			//添加logo
//			Graphics2D gs = image.createGraphics();
//			Image img = ImageIO.read(new File(QRcode.class.getClassLoader().getResource("logo.png").getPath()));
//			int widthLogo =img.getWidth(null);//img.getWidth(null)>image.getWidth()*2/10?(image.getWidth()*2/10):img.getWidth(null); 
//			int heightLogo =img.getHeight(null);//img.getHeight(null)>image.getHeight()*2/10?(image.getHeight()*2/10):img.getWidth(null); 
//			int x = (image.getWidth() - widthLogo) / 2;  
//	        int y = (image.getHeight() - heightLogo) / 2;  
//			gs.drawImage(img, x, y, widthLogo, heightLogo,null);
//			gs.dispose();
//			img.flush();
			image.flush();
			//写入流
			stream = new ByteArrayOutputStream();
			ImageIO.write(image,"jpg",stream);
			byte [] data =stream.toByteArray();
			//通过base64转码字符串
			Base64.Encoder base64 = Base64.getEncoder();
			String qrCode = base64.encodeToString(data);
			qrCode = qrCode.replaceAll("\r|\n", "");
			return qrCode;
		}catch(Exception e){
			return null;
		}finally{
			if(stream!=null){
				try {
					stream.close();
				} catch (IOException e) {
				}
			}
		}
	}
    private static BitMatrix deleteWhite(BitMatrix matrix){
        int[] rec = matrix.getEnclosingRectangle();  
        int resWidth = rec[2] + 1;  
        int resHeight = rec[3] + 1;  
      
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
        resMatrix.clear();  
        for (int i = 0; i < resWidth; i++) {  
            for (int j = 0; j < resHeight; j++) {  
                if (matrix.get(i + rec[0], j + rec[1]))  
                    resMatrix.set(i, j);  
            }  
        }  
        return resMatrix;  
    }
	
	
}
 


